import cgi
import wsgiref.handlers
import xml.dom.minidom

import YahooQuote
import YahooQuoteProvider

from UserService import UserService
from DateTimeService import DateTimeService

from google.appengine.ext import webapp
from google.appengine.api import urlfetch
from xml.dom.minidom import parseString

class YahooStockProvider:
	def get(self, symbol):
		# create args
		parmsDict = {
		    "s": "@^"+self.symbol.upper(),
		    "f": "sl1d1t1c1ohgv",
		    "e": ".csv",
		    "h": 0,
		    }
		parms = "&".join([("%s=%s" % (k,v)) for k,v in parmsDict.items()])

		# construct full URL
		url = "http://download.finance.yahoo.com/d/quotes.csv?%s" % parms

		# get the CSV for this index
		f = urllib.urlopen(url)
		lines = f.readlines()
		csvReader = csv.reader(lines)

		# extract the component symbols
		componentSymbols = [item[0].lower() for item in csvReader if item]

class ChartLink(webapp.RequestHandler):
	def get(self):
		market = YahooQuote.Market()
		symbol = cgi.escape(self.request.get('symbol'))
		stock = market[symbol]

		quotes=stock[20080407:20080414]
		data=[]
		for q in quotes:
			data+=str(q.close)
		tdata=','.join(data)
		
		url = '<img src="http://chart.apis.google.com/chart?\
			chs=250x200\
			&chd=t:%s\
			&cht=lc\
			&chl=Hello|World"/ >' % (tdata)
	
		self.response.out.write("""
			<html>
			<body>""")
		self.response.out.write(url) 
		self.response.out.write("""\"/>
		</div>
		<div><input type="submit" value="Get Quote">
		</div>
		</form>
		</body>
		</html>""")
		
class Chart(webapp.RequestHandler):
	def get(self):
		symbol = self.request.get('symbol')
		self.response.headers["Content-Type"] = "image/svg+xml"
		self.response.out.write(YahooQuoteProvider.createSVGCandlestickChart((2008,1,1), (2008,5,1), symbol))

class Quote(webapp.RequestHandler):
  def post(self):
    symbol = cgi.escape(self.request.get('symbol'))
    url = "http://www.webservicex.net/stockquote.asmx/GetQuote?symbol="+symbol
    #self.response.out.write(url)
    result = urlfetch.fetch(url) 
    xml=result.content.replace('&lt;', '<').replace('&gt;', '>')
    if result.status_code == 200:
        doc = parseString(xml)
        #self.response.out.write(result.content)
        #self.response.out.write(doc.documentElement.__dict__)
        #self.response.out.write(doc.getElementsByTagName('Last')[0].nodeValue)
        #last = doc.getElementsByTagName("Last")[0]
        #self.response.out.write(getText(last))
        symbol = doc.getElementsByTagName('Symbol')[0].firstChild.nodeValue
        name = doc.getElementsByTagName('Name')[0].firstChild.nodeValue
        last = doc.getElementsByTagName('Last')[0].firstChild.nodeValue
        volume = doc.getElementsByTagName('Volume')[0].firstChild.nodeValue
        pe = doc.getElementsByTagName('P-E')[0].firstChild.nodeValue
    
    self.response.out.write("""
      <html>
        <body>""")
    self.response.out.write(name)
    self.response.out.write("""
      <br/>
        last """)
    self.response.out.write(last)
    self.response.out.write("""
     <br/>
      volume """)
    self.response.out.write(volume)
    
    self.response.out.write("""
    <br/>
    <form action="/quote" method="post">
    <div><input type="text" name="symbol" value=\"""")
    self.response.out.write(symbol)
    self.response.out.write("""\"/>
	    </div>
            <div><input type="submit" value="Get Quote">
	    </div>
          </form>
        </body>
	</html>""")
    

class MainPage(webapp.RequestHandler):
  def get(self):
    self.response.out.write("""
      <html>
        <body>
          <form action="/quote" method="post">
            <div><input type="text" name="symbol" /></div>
            <div><input type="submit" value="Get Quote" /></div>
          </form>
        </body>
      </html>""")


def main():
	application = webapp.WSGIApplication(
	[('/', MainPage),
	('/quote', Quote),
	('/chartlink', ChartLink),
	('/service/chart', Chart),
	('/service/user', UserService),
	('/service/datetime', DateTimeService)],
	debug=True)
	wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()